<template>
  <div class="interact">
    <div class='tab-container'>
      <van-tabs
        v-model="activeIndex"
        color="#007AE6"
        :line-width="20"
        title-active-color="#007AE6"
        sticky
        animated
        :ellipsis="false"
        @click="onChange"
      >
        <van-tab
          v-for="item in tabs"
          :key="item.index"
          :title="item.label"
        ></van-tab>
      </van-tabs>
    </div>
    <div class="tab-box">
      <Tips v-if="listInfo.length"
      :isTool="false" title="互动客户" status="有" :increase="todayCount" :reduce="yesterdayCount" />
      <van-list
        v-model="loading"
        :finished="finished"
        :immediate-check="false"
        :finished-text="finished && !listInfo.length ? '' : '没有更多了'"
        @load="onLoad"
      >
        <div v-for="(item, index) in listInfo" :key="index">
          <div class="interact-item">
            <div class="interact-body van-hairline--bottom" @click="itemClickHandle(item)">
              <div class="left">
                <Avatar size="normal" :avatar="item.avatarUrl"></Avatar>
                <div class="content">
                  <div>
                    <span class='name ellipsis'>{{ item.clientName }}</span>
                    <span class="aw-tag">
                      <span v-if="item.clientStrangerFlag !== 2">访客</span>
                      <span class="active" v-else>意向客户</span>
                    </span>
                  </div>
                  <p>{{ item.lastTimeStr }}</p>
                </div>
              </div>
              <div class="right">
                {{ sourceTypes[item.sourceType] || '来自系统分配' }}
              </div>
            </div>
            <ul class="footer">
              <li class="btn-item" v-for="(list, index) in buttonList" :key="list.fun"
              :class="{ 'van-hairline--left': index }"
              :style="{ color: list.disabled && !item.clientMobile ? '#9BA4B4' :list.color }" @click="distribute(list, item)">
                <!-- <span class="icon-befoce" :style="{ backgroundImage: `url(${ list.iconUrl })` }"></span> -->
                <i class="iconfont" :class="list.icon"></i>
                <span>{{ list.name }}</span>
              </li>
            </ul>
          </div>
          <NewestDivider :isBgColor="true" v-if="findIndex == index" title="今日互动" />
        </div>
      </van-list>
    </div>
    <div class="no-data" v-if='!listInfo.length && finished'>
      <img src="@/assets/img/dynamics/dynamicsNull.png" alt="" >
      <p>暂无互动，赶紧去联系客户吧~ </p>
    </div>
    <van-popup v-model="popupVisible" position="bottom">
      <div class="popup-body">
        <h3 class="title">意向描述</h3>
        <textarea v-model="inputValue" maxlength="120" class="popup-main" placeholder="请输入客户意向信息" @blur="blurInput" />
      </div>
      <div class="popup-footer van-hairline--top">
        <span @click="cancel">取消</span>
        <span @click="savaDescribe" class="van-hairline--left">保存</span>
      </div>
    </van-popup>
  </div>
</template>

<script>
import Avatar from '@/components/Avatar'
import { mapGetters } from 'vuex'
import Tips from '@/components/Dynamics/Tips'
import CustomService from 'SERVICE/customService'
import commonService from 'SERVICE/commonService'
import NewestDivider from '@/components/Dynamics/NewestDivider'
const buttonList = [
  { icon: 'icon-kehu_xiaoxi', name: '发送消息', color: '#405170', fun: 'jumpClick' },
  { icon: 'icon-kehu_dadianhua', name: '打电话', color: '#405170', fun: 'setCustomer', disabled: true },
  { icon: 'icon-kehu_jianshu', name: '意向描述', color: '#405170', fun: 'showPopup' },
]

export default {
  data() {
    return {
      title: '互动数量',
      current: 1,
      size: 10,
      buttonList,
      popupVisible: false,
      activeIndex: 0,
      findIndex: 0,
      loading: false,
      finished: false,
      listInfo: [],
      scrollTop: 0,
      inputValue: '',
      tabs: [
        { index: 0, label: '我发起的聊天', value: "outChatCount" },
        { index: 1, label: '我的去电', value: "outCallCount" },
        { index: 2, label: '客户聊天', value: "inChatCount" },
        { index: 3, label: '客户来电', value: "inCallCount" }
      ],
      sourceTypes: {
        1: '来自名片分享',
        2: '来自楼盘分享',
        3: '来自文章分享',
      }
    }
  },
  components: {
    Tips,
    Avatar,
    NewestDivider
  },
  created() {
    let { todayCount, yesterdayCount, total } = this.$route.query
    this.todayCount = +todayCount || 0
    this.yesterdayCount = +yesterdayCount || 0
    let str = total ? `(${total})` : ""
    document.title = this.title + str
    this.getCacheData()
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  mounted() {
    this.$nextTick(() => {
      this.$el.querySelector(".tab-box").scrollTop = this.scrollTop
    })
  },
  methods: {
    onChange (index) {
      this.current = 1
      this.finished = false
      this.listInfo = []
      this.onLoad()
      if (index === this.tabs.length - 1) {
        let param = window.localStorage.getItem("firstShowToast")
        if (!param) {
          this.$toast("该数据来源于客户点击拨号！")
          window.localStorage.setItem("firstShowToast", "firstShowToast")
        }
      }
    },
    async getCustomerVo() {
      let countObj = await CustomService.getCustomerCommunicateVO()
      this.tabs.forEach(item => {
        item.label = item.label + "(" +countObj[item.value] + ")"
      })
    },
    jumpClick(list, item) {
      this.scrollTop = this.$el.querySelector(".tab-box").scrollTop
      sessionStorage.setItem('listInfo', JSON.stringify(this.$data))
      this.$router.push(`/custom/message/message?clientId=${item.clientId}`)
    },
    /**
     * 获取保存位置
     */
    getCacheData() {
      try {
        let data = sessionStorage.getItem('listInfo')
        if (data) {
          let obj = JSON.parse(data)
          for (const key in obj) {
            this[key] = obj[key]
          }
          sessionStorage.removeItem('listInfo')
        } else {
          this.onLoad()
          this.getCustomerVo()
        }
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * 打电话数据埋点上报
     */
    setCustomer(list, item) {
      if (item.clientMobile) {
        this.datacpReport(item)
        window.location.href = `tel:// ${item.clientAreaCode + item.clientMobile}`
      }
    },
    itemClickHandle(item) {
      this.scrollTop = this.$el.querySelector(".tab-box").scrollTop
      sessionStorage.setItem('listInfo', JSON.stringify(this.$data))
      let query = {}
      if (item.clientStrangerFlag !== 2) {
        query = { thread: 'thread' }
      } else {
        query = { activityTrack: 'activityTrack' }
      }
      this.$router.push({ path: `/custom/${item.clientId}`, query })
    },
    async datacpReport(item) {
      await commonService.datacpReport({
        userActionCode:"CPDDH",
        action: "",
        agentId: this.userInfo.agentId,
        clientId: item.clientId,
        clientName: item.clientName,
        enterpriseId: this.userInfo.enterpriseId,
        userActionType:"intention",
        entranceType: 0,
        sources: "qywx"
      })
    },
    distribute(list, item) {
      let str = list['fun']
      this.selectUser = item
      this[str](list, item)
    },
    blurInput() {
      window.scrollTo(0, 0)
    },
    showPopup(list, item) {
      if (item.clientStrangerFlag != 2) {
        this.$toast("请将该访客添加为意向客户后再进行设置")
        return false
      }
      this.popupVisible = true
      this.inputValue = item.intentionDescription
    },
    cancel() {
      this.inputValue = ''
      this.popupVisible = false
    },
    async savaDescribe() {
      let param = { clientId: this.selectUser.clientId, intentionDescription: this.inputValue }
      let res = await CustomService.updateCustomerInfo(param)
      this.popupVisible = false
      this.selectUser.intentionDescription = this.inputValue
      this.$toast({
        type: 'success',
        duration: 1000,
        message: '保存成功'
      })
    },
    async onLoad() {
      this.loading = true
      let result = await CustomService.getCustomerCommunicateList({ current: this.current, size: this.size, type: this.activeIndex + 1 })
      this.listInfo = this.listInfo.concat(result.records)
      this.findIndex = this.listInfo.findIndex(item => !item.ifToday) - 1
      if (result.pages <= this.current) {
        this.finished = true
      } else {
        this.current +=1
      }
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
.interact {
  .tab-box {
    overflow: scroll;
    height: calc(100% - 44px);
    background: #F7F9FA;
  }
}

.interact-item {
  background: #fff;
  height: 132px;
  box-sizing: border-box;
  font-size: 12px;
  // font-family: PingFangSC;
  font-weight: 500;
  margin-top: 12px;
  .interact-body {
    color: rgba(156, 165, 181, 1);
    padding: 20px 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: inset 0px -1px 1px -1px #E4E6F0;
    .left {
      display: flex;
      flex: 1;
      .content {
        padding-left: 12px;
        div {
          display: flex;
          align-items: center;
        }
        .name {
          font-size: 16px;
          font-family: PingFangSC-Semibold;
          font-weight: 500;
          color: #13284D;
          height: 24px;
          line-height: 24px;
          margin-right: 6px;
          max-width: 120px;
          display: inline-block;
        }
        p {
          height: 16px;
          line-height: 16px;
          margin-top: 4px;
        }
      }
    }
    .right {
      text-align: center;
      margin-left: 15px;
      color: #9BA4B4;
      font-size: 14px;
    }
  }
  .footer {
    padding: 10px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .btn-item {
      flex: 1;
      align-items: center;
      height: 24px;
      line-height: 24px;
      text-align: center;
      color: rgba(133, 145, 166, 1);
      span {
        margin-left: 4px;
        vertical-align: top;
      }
      // .icon-befoce {
      //   vertical-align: text-top;
      //   margin-right: 5px;
      //   display: inline-block;
      //   width: 16px;
      //   height: 16px;
      //   background-size: cover;
      //   background-repeat: no-repeat;
      //   background-position: center;
      // }
    }
  }
  .ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.no-data {
  width: 100%;
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -40%);
  font-size: 12px;
  font-family: PingFangSC;
  font-weight: 400;
  color: rgba(153, 153, 153, 1);
  text-align: center;
  height: 17px;
  line-height: 17px;
  img {
    width: 88px;
    height: 88px;
  }
}

.van-popup {
  .popup-body {
    height: 200px;
    padding: 0 16px;
    .title {
      display: flex;
      align-items: center;
      justify-content: center;
      color: #13284D;
      font-size: 18px;
      height: 50px;
    }
    .popup-main {
      height: 120px;
      width: 100%;
      border-color: #E4E6F0;
      padding: 8px;
      line-height: 20px;
      font-size: 14px;
      outline: none;
      -webkit-appearance: none; 
      &:focus{
        border-color: #007AE6;
      }
    }
  }
  .popup-footer {
    height: 50px;
    font-size: 18px;
    color: #9BA4B4;
    span {
      flex: 1;
      float: left;
      width: 50%;
      line-height: 50px;
      text-align: center;
      &:last-child {
        color: #007AE6;
      }
      &:active {
        background: #ccc;
      }
    }
  }
}

.aw-tag {
  font-size: 10PX;
  line-height: normal;
  display: inline-table;
  // vertical-align: text-bottom;
  font-family: 'Microsoft YaHei', 'PingFangSC-Regular';
  span {
    display: table-cell;
    vertical-align: middle;
    padding: 0 4px;
    border-radius: 2px;
    background: rgba(156, 165, 181, 0.15);
    color: #40516f;
    &.active {
      color: #007ae6;
      background: rgba(0, 122, 230, 0.15);
    }
  }
}


.van-dialog__header {
  color: #333;
  font-family: PingFangSC;
  font-weight: 500;
}
.van-dialog__message{
  font-family: PingFangSC;
  font-weight: 400;
  color: #333;
}
.van-dialog__cancel span {
  color: #007ae6;
}
.van-dialog__confirm span {
  color: #ea4d2e;
}

/deep/ .van-tabs__nav--line {
  padding-left: 5px;
  padding-right: 5px;
  .van-tab {
    padding: 0 10px;
  }
}
</style>